package controller

import (
	. "gddgame.cc/galaxy/common/dsl/web"
	"gddgame.cc/galaxy/core/models"
	"gddgame.cc/galaxy/server/web"
	"gddgame.cc/galaxy/utils/def"
)

func Get(context def.Context, managerId int) (*models.Manager, error) {
	var manager models.Manager
	if ok, err := models.ManagerModel.PK(managerId).One(&manager); !ok {
		return nil, EmptyExceptionDetail("manager不存在", err)
	}
	return &manager, nil
}

func List(context def.Context, page int, number int) (*web.PageResult, error) {
	var managers []models.Manager
	var err error
	count, err := models.ManagerModel.Query().FindAndCount(&managers, page, number)
	if err != nil {
		return nil, SystemExceptionDetail("列表错误", err)
	}
	return &web.PageResult{managers, page, int(count)}, nil
}

func Add(context def.Context, username string) error {
	var manager models.Manager
	var err error
	if ok, err := models.ManagerModel.Query().Where("=", "username", username).One(&manager); ok {
		return ValidExceptionDetail("用户名已存在", err)
	}
	password := manager.FormatPassword("000000")
	manager = models.Manager{
		Username: username,
		Password: password,
	}
	_, err = models.ManagerModel.Insert(&manager)
	if err != nil {
		return SystemExceptionDetail("用户添加失败", err)
	}
	return nil
}

func Edit(context def.Context, managerId int, data map[string]interface{}) error {
	var manager models.Manager
	var err error
	if ok, err := models.ManagerModel.PK(managerId).One(&manager); !ok {
		return EmptyExceptionDetail("manager不存在", err)
	}
	if password, ok := data["password"]; ok {
		data["password"] = manager.FormatPassword(password.(string))
	}
	_, err = models.ManagerModel.PK(managerId).Update(data)
	if err != nil {
		return SystemExceptionDetail("管理员更新失败", err)
	}
	return nil
}

func Delete(context def.Context, managerId int) error {
	var manager models.Manager
	var err error
	if ok, err := models.ManagerModel.PK(managerId).One(&manager); !ok {
		return EmptyExceptionDetail("manager不存在", err)
	}
	_, err = models.ManagerModel.PK(managerId).Delete()
	if err != nil {
		return SystemExceptionDetail("管理员删除失败", err)
	}
	return nil
}
